<template>
  <div class="code-formatter-tool">
    <div class="tool-header">
      <h1>代码格式化</h1>
      <p>格式化各种编程语言代码</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 格式化主体 -->
        <el-col :span="16">
          <div class="formatter-section">
            <!-- 语言选择 -->
            <div class="language-selector">
              <h3>选择编程语言</h3>
              <div class="language-tabs">
                <div 
                  v-for="lang in languages" 
                  :key="lang.value"
                  class="language-tab"
                  :class="{ active: selectedLanguage === lang.value }"
                  @click="selectLanguage(lang.value)"
                >
                  <div class="lang-icon">{{ lang.icon }}</div>
                  <div class="lang-name">{{ lang.name }}</div>
                </div>
              </div>
            </div>
            
            <!-- 代码输入 -->
            <div class="code-input">
              <h3>代码输入</h3>
              <div class="input-actions">
                <el-button @click="pasteCode" size="small">
                  <el-icon><DocumentCopy /></el-icon>
                  粘贴代码
                </el-button>
                <el-button @click="clearCode" size="small">
                  清空
                </el-button>
                <el-button @click="loadSample" size="small">
                  加载示例
                </el-button>
              </div>
              <div class="code-editor">
                <el-input
                  v-model="inputCode"
                  type="textarea"
                  :rows="15"
                  placeholder="请输入要格式化的代码..."
                  class="code-textarea"
                />
              </div>
            </div>
            
            <!-- 格式化选项 -->
            <div class="format-options">
              <h3>格式化选项</h3>
              <div class="options-grid">
                <div class="option-group">
                  <label>缩进类型：</label>
                  <el-select v-model="formatOptions.indentType" size="small">
                    <el-option label="空格" value="space" />
                    <el-option label="制表符" value="tab" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>缩进大小：</label>
                  <el-select v-model="formatOptions.indentSize" size="small">
                    <el-option label="2" :value="2" />
                    <el-option label="4" :value="4" />
                    <el-option label="8" :value="8" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>行长度：</label>
                  <el-input-number v-model="formatOptions.lineLength" :min="40" :max="200" size="small" />
                </div>
                <div class="option-group">
                  <label>引号类型：</label>
                  <el-select v-model="formatOptions.quoteType" size="small">
                    <el-option label="单引号" value="single" />
                    <el-option label="双引号" value="double" />
                  </el-select>
                </div>
              </div>
            </div>
            
            <!-- 格式化按钮 -->
            <div class="format-actions">
              <el-button @click="formatCode" type="primary" size="large" :loading="isFormatting" :disabled="!inputCode.trim()">
                <el-icon><Edit /></el-icon>
                格式化代码
              </el-button>
              <el-button @click="copyResult" size="large" :disabled="!formattedCode">
                <el-icon><DocumentCopy /></el-icon>
                复制结果
              </el-button>
              <el-button @click="downloadResult" size="large" :disabled="!formattedCode">
                <el-icon><Download /></el-icon>
                下载文件
              </el-button>
            </div>
            
            <!-- 格式化结果 -->
            <div class="format-result" v-if="formattedCode">
              <h3>格式化结果</h3>
              <div class="result-info">
                <div class="info-item">
                  <span class="info-label">原始行数：</span>
                  <span class="info-value">{{ originalLines }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">格式化后行数：</span>
                  <span class="info-value">{{ formattedLines }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">字符数：</span>
                  <span class="info-value">{{ formattedCode.length }}</span>
                </div>
              </div>
              <div class="result-editor">
                <el-input
                  v-model="formattedCode"
                  type="textarea"
                  :rows="15"
                  readonly
                  class="code-textarea"
                />
              </div>
            </div>
            
            <!-- 格式化历史 -->
            <div class="format-history">
              <h3>格式化历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in formatHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-lang">{{ item.language }}</div>
                  <div class="history-info">
                    <span class="history-lines">{{ item.lines }} 行</span>
                    <span class="history-time">{{ item.time }}</span>
                  </div>
                </div>
                <div v-if="formatHistory.length === 0" class="empty-history">
                  暂无格式化历史
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>支持的语言</h3>
            </div>
            
            <div class="supported-languages">
              <div 
                v-for="lang in languages" 
                :key="lang.value"
                class="lang-item"
                @click="selectLanguage(lang.value)"
              >
                <div class="lang-icon">{{ lang.icon }}</div>
                <div class="lang-info">
                  <div class="lang-name">{{ lang.name }}</div>
                  <div class="lang-ext">{{ lang.extension }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>支持的语言：</h4>
                <ul>
                  <li><strong>JavaScript：</strong> ES6+语法支持</li>
                  <li><strong>Python：</strong> PEP8规范</li>
                  <li><strong>Java：</strong> 标准Java格式</li>
                  <li><strong>C++：</strong> 标准C++格式</li>
                  <li><strong>HTML：</strong> 标签格式化</li>
                  <li><strong>CSS：</strong> 样式格式化</li>
                  <li><strong>JSON：</strong> 数据格式化</li>
                </ul>
                
                <h4>格式化选项：</h4>
                <ul>
                  <li><strong>缩进类型：</strong> 空格或制表符</li>
                  <li><strong>缩进大小：</strong> 2/4/8个字符</li>
                  <li><strong>行长度：</strong> 40-200字符</li>
                  <li><strong>引号类型：</strong> 单引号或双引号</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 格式化会改变代码结构</p>
                  <p>⚠️ 请确保代码语法正确</p>
                  <p>⚠️ 建议先备份原始代码</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy, Edit, Download } from '@element-plus/icons-vue'

const selectedLanguage = ref('javascript')
const inputCode = ref('')
const formattedCode = ref('')
const isFormatting = ref(false)
const formatHistory = ref([])

const formatOptions = ref({
  indentType: 'space',
  indentSize: 2,
  lineLength: 80,
  quoteType: 'single'
})

const languages = [
  { value: 'javascript', name: 'JavaScript', icon: '🟨', extension: '.js' },
  { value: 'python', name: 'Python', icon: '🐍', extension: '.py' },
  { value: 'java', name: 'Java', icon: '☕', extension: '.java' },
  { value: 'cpp', name: 'C++', icon: '⚙️', extension: '.cpp' },
  { value: 'html', name: 'HTML', icon: '🌐', extension: '.html' },
  { value: 'css', name: 'CSS', icon: '🎨', extension: '.css' },
  { value: 'json', name: 'JSON', icon: '📄', extension: '.json' }
]

const originalLines = computed(() => {
  return inputCode.value ? inputCode.value.split('\n').length : 0
})

const formattedLines = computed(() => {
  return formattedCode.value ? formattedCode.value.split('\n').length : 0
})

const sampleCodes = {
  javascript: `function fibonacci(n){if(n<=1)return n;return fibonacci(n-1)+fibonacci(n-2);}const result=fibonacci(10);console.log(result);`,
  python: `def fibonacci(n):\nif n<=1:return n\nreturn fibonacci(n-1)+fibonacci(n-2)\nresult=fibonacci(10)\nprint(result)`,
  java: `public class Fibonacci{public static int fibonacci(int n){if(n<=1)return n;return fibonacci(n-1)+fibonacci(n-2);}public static void main(String[]args){int result=fibonacci(10);System.out.println(result);}}`,
  cpp: `#include<iostream>\nusing namespace std;\nint fibonacci(int n){if(n<=1)return n;return fibonacci(n-1)+fibonacci(n-2);}\nint main(){int result=fibonacci(10);cout<<result<<endl;return 0;}`,
  html: `<html><head><title>Test</title></head><body><h1>Hello World</h1><p>This is a test page.</p></body></html>`,
  css: `.container{width:100%;height:100vh;background-color:#f0f0f0;display:flex;justify-content:center;align-items:center;}`,
  json: `{"name":"test","age":25,"hobbies":["reading","coding"],"address":{"city":"Beijing","country":"China"}}`
}

const selectLanguage = (lang) => {
  selectedLanguage.value = lang
  ElMessage.success(`已选择：${languages.find(l => l.value === lang)?.name}`)
}

const pasteCode = async () => {
  try {
    const text = await navigator.clipboard.readText()
    inputCode.value = text
    ElMessage.success('代码已粘贴')
  } catch (error) {
    ElMessage.error('无法访问剪贴板')
  }
}

const clearCode = () => {
  inputCode.value = ''
  formattedCode.value = ''
  ElMessage.info('代码已清空')
}

const loadSample = () => {
  inputCode.value = sampleCodes[selectedLanguage.value] || ''
  ElMessage.success('示例代码已加载')
}

const formatCode = async () => {
  if (!inputCode.value.trim()) {
    ElMessage.warning('请输入要格式化的代码')
    return
  }
  
  isFormatting.value = true
  
  try {
    // 模拟格式化过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 简单的格式化逻辑
    let formatted = inputCode.value
    
    switch (selectedLanguage.value) {
      case 'javascript':
        formatted = formatJavaScript(inputCode.value)
        break
      case 'python':
        formatted = formatPython(inputCode.value)
        break
      case 'java':
        formatted = formatJava(inputCode.value)
        break
      case 'cpp':
        formatted = formatCpp(inputCode.value)
        break
      case 'html':
        formatted = formatHtml(inputCode.value)
        break
      case 'css':
        formatted = formatCss(inputCode.value)
        break
      case 'json':
        formatted = formatJson(inputCode.value)
        break
    }
    
    formattedCode.value = formatted
    
    // 添加到历史
    addToHistory()
    
    ElMessage.success('代码格式化完成')
    
  } catch (error) {
    ElMessage.error('格式化失败：' + error.message)
  } finally {
    isFormatting.value = false
  }
}

const formatJavaScript = (code) => {
  // 简单的JavaScript格式化
  return code
    .replace(/;/g, ';\n')
    .replace(/\{/g, ' {\n')
    .replace(/\}/g, '\n}\n')
    .replace(/,/g, ',\n')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .map((line, index) => '  '.repeat(Math.floor(index / 2)) + line)
    .join('\n')
}

const formatPython = (code) => {
  // 简单的Python格式化
  return code
    .replace(/:/g, ':\n')
    .replace(/def /g, '\ndef ')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .join('\n')
}

const formatJava = (code) => {
  // 简单的Java格式化
  return code
    .replace(/\{/g, ' {\n')
    .replace(/\}/g, '\n}\n')
    .replace(/;/g, ';\n')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .map((line, index) => '  '.repeat(Math.floor(index / 3)) + line)
    .join('\n')
}

const formatCpp = (code) => {
  // 简单的C++格式化
  return code
    .replace(/\{/g, ' {\n')
    .replace(/\}/g, '\n}\n')
    .replace(/;/g, ';\n')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .map((line, index) => '  '.repeat(Math.floor(index / 3)) + line)
    .join('\n')
}

const formatHtml = (code) => {
  // 简单的HTML格式化
  return code
    .replace(/></g, '>\n<')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .map((line, index) => '  '.repeat(Math.floor(index / 2)) + line)
    .join('\n')
}

const formatCss = (code) => {
  // 简单的CSS格式化
  return code
    .replace(/\{/g, ' {\n')
    .replace(/\}/g, '\n}\n')
    .replace(/;/g, ';\n')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line)
    .map((line, index) => '  '.repeat(Math.floor(index / 2)) + line)
    .join('\n')
}

const formatJson = (code) => {
  try {
    const obj = JSON.parse(code)
    return JSON.stringify(obj, null, formatOptions.value.indentSize)
  } catch {
    return code
  }
}

const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(formattedCode.value)
    ElMessage.success('结果已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const downloadResult = () => {
  const lang = languages.find(l => l.value === selectedLanguage.value)
  const filename = `formatted_code${lang?.extension || '.txt'}`
  
  const blob = new Blob([formattedCode.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件已下载')
}

const addToHistory = () => {
  const historyItem = {
    language: languages.find(l => l.value === selectedLanguage.value)?.name || selectedLanguage.value,
    lines: formattedLines.value,
    time: new Date().toLocaleString('zh-CN')
  }
  
  formatHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (formatHistory.value.length > 20) {
    formatHistory.value = formatHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  ElMessage.success(`已加载：${item.language} 格式化历史`)
}
</script>

<style scoped>
.code-formatter-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.formatter-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.language-selector,
.code-input,
.format-options,
.format-actions,
.format-result,
.format-history {
  margin-bottom: 30px;
}

.language-selector h3,
.code-input h3,
.format-options h3,
.format-result h3,
.format-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.language-tabs {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
}

.language-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 2px solid #e9ecef;
  background: #f8f9fa;
}

.language-tab:hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.language-tab.active {
  border-color: #667eea;
  background: #f0f4ff;
}

.lang-icon {
  font-size: 2rem;
  margin-bottom: 8px;
}

.lang-name {
  font-size: 0.9rem;
  font-weight: 500;
  color: #333;
}

.input-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.code-editor {
  position: relative;
}

.code-textarea {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-group label {
  font-weight: 500;
  color: #666;
}

.format-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.result-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.info-value {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.result-editor {
  position: relative;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-lang {
  font-size: 1rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.history-info {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #666;
}

.history-lines {
  color: #667eea;
  font-weight: 500;
}

.history-time {
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.supported-languages {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.lang-item {
  display: flex;
  align-items: center;
  gap: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.lang-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.lang-icon {
  font-size: 1.5rem;
}

.lang-name {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.lang-ext {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .language-tabs {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .options-grid {
    grid-template-columns: 1fr;
  }
  
  .format-actions {
    flex-direction: column;
  }
  
  .result-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .history-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
